<!--
  组件：map 地图初始化
  作者：kuake
  时间：2023年01月02日
  网址：https://gis.1024ape.com
  系统：WebGIS 地理信息平台
-->
<template>
	<div ref="map" class="map"></div>
</template>

<script>
import 'ol/ol.css'
import { Feature, Map, View } from 'ol'
import VectorLayer from 'ol/layer/Vector'
import VectorSource from 'ol/source/Vector'
import { Polygon, Point } from 'ol/geom'
import { Style, Stroke, Fill } from 'ol/style'
import { mapActions } from 'pinia'
import { useMapStore } from '../../stores/mapStore'
export default {
	name: 'FmMap',
	props: {
		zoom: {
			type: Number,
			default: 1
		},
		center: {
			type: Array,
			default: () => [0, 0]
		}
	},
	mounted() {
		this.initMap()
	},
	methods: {
		...mapActions(useMapStore, ['setMap']),
		initMap() {
			this.map = new Map({
				target: this.$refs.map,
				view: new View({
					center: this.center,
					zoom: this.zoom
				})
			})
			this.setMap(this.map)
			const layer = new VectorLayer({
				source: new VectorSource()
			})
			const feature = new Feature(new Point([0, 0]))
			layer.getSource().addFeature(feature)
			this.map.addLayer(layer)
			this.drawHexagonGrid(this.map)
		},
		drawHexagonGrid(map) {
			const hexagonLayer = new VectorLayer({
				source: new VectorSource(),
				style: new Style({
					stroke: new Stroke({
						color: 'rgba(65, 0, 0, 0.8)',
						width: 1
					}),
					fill: new Fill({
						color: 'rgba(255, 0, 0, 0)'
					})
				})
			})

			const hexagonSource = hexagonLayer.getSource()

			// 计算六边形的中心点坐标和边长
			const center = [0, 0] // 六边形中心点坐标
			const radius = 1000000 // 六边形边长

			// 循环生成六边形网格
			for (let i = 1; i < 10; i++) {
				for (let j = 1; j < 10; j++) {
					const hexagonCoords = this.generateHexagonCoords(center, radius)
					const hexagon = new Polygon([hexagonCoords])
					const feature = new Feature(hexagon)
					hexagonSource.addFeature(feature)

					// 根据网格位置进行偏移，以便形成蜂窝网格效果
					center[0] += radius * 1.5
					center[1] += (radius * Math.sqrt(3)) / 2
				}

				// 每行结束后重新调整偏移位置
				center[0] = 0
				center[1] = radius * Math.sqrt(3) * i
			}

			this.map.addLayer(hexagonLayer)
		},
		generateHexagonCoords(center, radius) {
			const coords = []

			for (let i = 0; i < 6; i++) {
				const angle = (Math.PI / 3) * i
				const x = center[0] + radius * Math.cos(angle)
				const y = center[1] + radius * Math.sin(angle)
				coords.push([x, y])
			}

			return coords
		}
	}
}
</script>

<style lang="scss">
.map {
	width: 100%;
	position: absolute;
	top: 0px;
	bottom: 0;
}
</style>
